<template>
    <div class="login">
        <div class="login-from">
            <div class="message">
                <div class="login-title">登录</div>
                <div class="to-register">
                    还没有账号？<span @click="useLoginStore.setActive()"
                        >免费注册</span
                    >
                </div>
            </div>
        </div>
        <div class="register-from-data">
            <el-card shadow="hover">
                <el-form status-icon :model="data.form" :rules="data.formRules">
                    <el-form-item prop="username">
                        <el-input
                            v-model.trim="data.form.username"
                            placeholder="请输入邮箱/手机号"
                            autocomplete="off"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            type="password"
                            v-model.trim="data.form.password"
                            placeholder="请输入密码"
                            autocomplete="off"
                            show-password
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="code">
                        <el-input
                            style="width: 160px"
                            v-model.trim="data.form.code"
                            placeholder="请输入4位验证码"
                        ></el-input>
                        <div class="code">
                            <Sidentify
                                :identifyCode="identifyCode"
                                @click="refreshCode"
                            />
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            @click="onSubmit(data.form)"
                            style="
                                width: 100px;
                                color: aliceblue;
                                transform: translateX(160px);
                            "
                            color="rgb(220,170,91)"
                            >登录</el-button
                        >
                        <a href="javascript:;" class="forgot-password"
                            >忘记密码?</a
                        >
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import md5 from 'js-md5'
import { ElMessage } from 'element-plus'
import { userAccountLogin } from '@/apis/user'
import {
    validateEmailOrTelephone,
    validateCode,
    validatePassword,
} from '@/utils/validate'
import { watch, reactive, ref, onMounted } from 'vue'
import { loginStore } from '@/stores/login'
import { userStore } from '@/stores/user'
import { ElNotification } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const useUserStore = userStore()
const useLoginStore = loginStore()
// 图形验证码
let identifyCodes = '1234567890'
let identifyCode = ref('')

const randomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min)
}

const makeCode = (o, l) => {
    for (let i = 0; i < l; i++) {
        identifyCode.value += o[randomNum(0, o.length)]
    }
}

const refreshCode = () => {
    identifyCode.value = ''
    makeCode(identifyCodes, 4)
}

onMounted(() => {
    identifyCode.value = ''
    makeCode(identifyCodes, 4)
})

// 用户名校验
const validateNameRules = (rule, value, callback) => {
    let regEmailOrTelephone = validateEmailOrTelephone(value)
    if (value === '') {
        callback(new Error('请输入邮箱或手机号'))
    } else if (!regEmailOrTelephone) {
        callback(new Error('邮箱格式不正确'))
    } else {
        callback()
    }
}

// 验证码校验
const validateCodeRules = (rule, value, callback) => {
    let regCode = validateCode(value)
    if (value === '') {
        callback(new Error('请输入4位验证码'))
    } else if (!regCode) {
        callback(new Error('验证码格式不正确'))
    } else {
        callback()
    }
}
// 登录表单数据
const data = reactive({
    form: { username: '', password: '', code: identifyCode.value },
    formRules: {
        username: [{ validator: validateNameRules, trigger: 'change' }],
        password: [
            { required: true, message: '请输入密码', trigger: 'change' },
        ],
        code: [{ validator: validateCodeRules, trigger: 'change' }],
    },
})

const onSubmit = formData => {
    const username = formData.username
    const password = formData.password
    const code = formData.code
    // 校验用户名
    if (!validateEmailOrTelephone(username)) {
        ElNotification({
            title: '提示',
            message: '用户名不能为空或格式不正确',
            type: 'warning',
        })
        return false
    }
    // 校验密码
    if (!validatePassword(password)) {
        ElNotification({
            title: '提示',
            message: '登录密码错误，请重试',
            type: 'warning',
        })
        return false
    }
    // 校验验证码
    if (!validateCode(code)) {
        ElNotification({
            title: '提示',
            message: '验证码不能为空或格式不正确',
            type: 'warning',
        })
        return false
    }
    if (code != identifyCode.value) {
        ElNotification({
            title: '提示',
            message: '验证码错误',
            type: 'warning',
        })
        return false
    }
    // 最后提交到后端
    userAccountLogin({ username, password: md5(password) })
        .then(res => {
            if (res.city == null) {
                res.city = '{}'
            }
            //    登录成功之后 存token 提示  跳转
            const {
                id,
                city,
                username,
                avatar,
                token,
                mobile,
                nickname,
                gender,
                occupation,
                birthday,
            } = res
            useUserStore.setUser({
                id,
                city: JSON.parse(city.replace(/\\/, '')),
                username,
                avatar,
                token,
                mobile,
                nickname,
                gender,
                occupation,
                birthday,
            })
            ElMessage({
                type: 'success',
                message: '登录成功！',
            })
            router.push(route.query.redirectUrl || '/')
        })
        .catch(err => {
            ElMessage({
                showClose: true,
                message: err?.response?.data?.msg,
                type: 'error',
            })
        })
}
</script>

<style lang="scss" scoped>
.login {
    width: 300px;
    height: 300px;
    .message {
        .login-title {
            font-size: 36px;
        }
        .to-register {
            span {
                color: rgb(72, 135, 207);
                cursor: pointer;
                user-select: none;
                transition: all 0.3s ease;
                height: 20px;
                margin-top: 10px;
            }
        }
    }
    .register-from-data {
        margin-top: 20px;
        height: 230px;
        .el-card {
            height: 100%;
        }
    }
}
.el-form-item {
    margin-bottom: 20px;
}
.code {
    position: absolute;
    right: 10px;
    margin-top: 11px;
    overflow: hidden;
}
.forgot-password {
    color: rgb(110, 110, 110);
    font-size: 12px;
    transform: translateX(-95px);
    text-decoration: none;
    &:hover {
        text-decoration: underline;
    }
}
</style>
